import { ref } from 'vue'
import store from '@/store'
import { defineStore } from 'pinia'
import { getToken, getUserInfo, removeToken, setToken, setUserInfo } from '@/utils/local-storage'
import { resetRouter } from '@/router'
import { postLogin } from '@/api/login'

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken() || '')
  const username = ref(getUserInfo()?.username || '')

  const login = data => postLogin(data).then(res => {
    if (res.token) {
      setToken(res.token)
      token.value = res.token
      setUserInfo(res)
      username.value = res.username
    }
    return res
  })

  const logout = () => {
    removeToken()
    token.value = ''
    resetRouter()
  }
  const resetToken = () => {
    removeToken()
    token.value = ''
  }

  return { token, username, login, logout, resetToken }
})
export function useUserStoreHook() {
  return useUserStore(store)
}
